var express = require('express');
var router = express.Router();
var path = require("path");
var cartServ = require(path.join(process.cwd(), "/services/CartService"));

/**
 * 【增】添加购物车
 * this.$http.post('/insert',{
 *     user_id: "", good_id: "", good_count: "",
 *     cat_one_id: "", cat_two_id: "", cat_three_id: "",
 * })
 * 
 */
router.post("/insert", function (req, res, next) {
	cartServ.createCart({
		"user_id": req.body.user_id,
		"good_id": req.body.good_id,
		"good_count": req.body.good_count,
		"good_sku": req.body.good_sku || [],
		"cat_one_id": req.body.cat_one_id,
		"cat_two_id": req.body.cat_two_id,
		"cat_three_id": req.body.cat_three_id,
	}, function (err, result) {
		if (err) return res.sendResult(null, err.code, err.msg, err.stack);
		res.sendResult(result.data, result.code, result.msg, null);
	});
});

/** 
 * 【删】单个物理删除
 * this.$http.delete('/delete/12')
 */
router.delete("/delete/:id", function (req, res, next) {
	cartServ.deleteCart(req.params.id, function (err, result) {
		if (err) return res.sendResult(null, err.code, err.msg, err.stack);
		res.sendResult(result.data, result.code, result.msg, null);
	});
});

/** 
 * 【删】批量物理删除
 * this.$http({
 *     method:'delete',
 *     url:'/batchDelete',
 * 	   data:{
 * 		 ids:[]
 * 	   }
 * })
 */
router.delete("/batchDelete", function (req, res, next) {
	cartServ.deleteCart(req.body.ids, function (err, result) {
		if (err) return res.sendResult(null, err.code, err.msg, err.stack);
		res.sendResult(result.data, result.code, result.msg, null);
	});
});

/** 
 * 【改】更新购物车数量
 * this.$http.put('/update/' + item.id,{
 *     good_count: ""
 * })
 */
router.put("/update/:id", function (req, res, next) {
	cartServ.updateCart(req.params.id, req.body.good_count, function (err, result) {
		if (err) return res.sendResult(null, err.code, err.msg, err.stack);
		res.sendResult(result.data, result.code, result.msg, null);
	});
});

/** 
 * 【查】分页查询
 * this.$http({
 *		url:'/getPage', 
 *		method:'post',
 *		params: this.queryInfo,
 * })
 */
router.post("/getPage", function (req, res, next) {
	var conditions = {
		"where": {
			user_id: req.userInfo.uid
		},
		"pagenum": req.query.pagenum,
		"pagesize": req.query.pagesize
	}
	cartServ.getPageCarts(conditions, function (err, result) {
		if (err) return res.sendResult(null, err.code, err.msg, err.stack);
		res.sendResult(result.data, result.code, result.msg, null);
	});
});

/** 
 * 【查】搜索查询
 * this.$http({
 *		url:'/getSearch', 
 *		method:'post',
 *		data: { ids:[] },
 * })
 */
router.post("/getSearch", function (req, res, next) {
	var conditions = {
		"where": {
			user_id: req.userInfo.uid
		},
	}
	if (req.body.ids && Array.isArray(req.body.ids)) {
		conditions.where.id = {
			$in: req.body.ids
		}
	}
	cartServ.getSearchCarts(conditions, function (err, result) {
		if (err) return res.sendResult(null, err.code, err.msg, err.stack);
		res.sendResult(result.data, result.code, result.msg, null);
	});
});

module.exports = router;